#!/bin/bash
#!/usr/bin/env bash
set -e

export buildType="${1}"
export curDir=$(cd $(dirname $0); pwd -P)
export projPath=$(realpath $curDir/../..)

cangjieTarget="aarch64-apple-ios"
cangjieFeatures="feature.env.gnu"
export IOS_CJ_FRONTEND="$CJMP_SDK_HOME/cjmp-ui/ios"
export CANGJIE_IOS_PATH="$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-ios"
export IOS_PACKAGE="${projPath}/package/target/aarch64-apple-ios/${buildType}/pkgnative_windows"

if [[ "${buildType}" == "debug" ]]; then
    cangjieExtraArgs="-g"
else
    cangjieExtraArgs=""
fi

cd "${projPath}/ios/cangjie"
source "$CJMP_SDK_HOME/cjmp-tools/third_party/cangjie-ios/envsetup.sh"
cjpm build --no-feature-deduce --target="${cangjieTarget}" ${cangjieExtraArgs}

outputDir="${projPath}/ios/Frameworks"
mkdir -p "${outputDir}"
soFilePath="${projPath}/ios/cangjie/target/${cangjieTarget}/${buildType}/occallcj/liboccallcj.so"

if [[ ! -f "${soFilePath}" ]]; then
    echo "Error: Cannot find output library at ${soFilePath}" >&2
    exit 1
fi

cp "${soFilePath}" "${outputDir}/liboccallcj.dylib"
cp "${CANGJIE_IOS_PATH}/runtime/lib/ios_aarch64_cjnative/libcangjie-runtime.dylib" "${outputDir}"
cp "${CANGJIE_IOS_PATH}/runtime/lib/ios_aarch64_cjnative/libcangjie-std-core.dylib" "${outputDir}"
cp "${CANGJIE_IOS_PATH}/runtime/lib/ios_aarch64_cjnative/libsecurec.dylib" "${outputDir}"
cd -
